'use strict';

const dbUtility = require('./dbUtility');
const msgUtility = require('./msgUtility');
const gpUtility = require('./gpUtility');
const logUtility = require('./logUtility.js');

// 配置日志
logUtility.configure();
const logger = logUtility.logger('app');

/**
 * 启动信息发送服务
 */
function begin() {
    logger.info('*****MESSAGE SERVER IS RUNNING...*****');
    setInterval(beginSendMsg, 60000);
}

/**
 * 开始发送信息
 */
function beginSendMsg() {
    logger.info('**********BEGIN SEND MSG**********');
    gpUtility.excuteGP(sendMsg);
}

/**
 * 执行发送信息
 */
function* sendMsg() {
    try {
        //取得需要发送的短信
        let needSendMsgs = yield dbUtility.msgModel.getNeedSendMsg();
        //逐个发送短信
        for (let msg of needSendMsgs) {
            logger.info('Send Msg Info:');
            logger.info(msg);

            let expCab = yield* dbUtility.getExpCabByExpNo(msg.expNo, dbUtility.expModel, dbUtility.cabModel);
            let msgIdStatus = yield* msgUtility.sendSmsGP(expCab.exp, expCab.cab);
            yield* dbUtility.updateMsgId(msg.expNo, msgIdStatus.msgId, msgIdStatus.msgStatus, dbUtility.msgModel);

            //暂停10秒之后发送下一个
            sleep(10000)
        }
        //转移发送状态
        yield* dbUtility.transferMsgStatusToExp(dbUtility.expModel, dbUtility.msgModel);
    } catch (e) {
        logger.error(e)
    }
}

/**
 * 当前进程休眠固定毫秒数
 * 
 * @param {Number}milliseconds 休眠毫秒数
 */
function sleep(milliseconds) {
    let getCurrentTime = function() {
        return (new Date()).getTime();
    }

    let startTime = getCurrentTime();
    let endTime = startTime + milliseconds;
    while (endTime > getCurrentTime());
}

module.exports.begin = begin;